import axios from 'axios'
import { MessageBox, Message, Notification  } from 'element-ui'
import store from '@/store'


const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, 
  timeout: 180000
})

//添加post已query参数提交
service.postQuery = (url, params, config = {})=>{
  return service({
    url:url,
    method: 'post',
    params: params
  })
}

// request拦截器
service.interceptors.request.use(
  config => {
    if (store.state.useInfo) {
      config.headers['token'] = store.state.useInfo.F_ID//登陆的用户id
    }else{
      config.headers['token'] = 'default'//默认id
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    if (res.code && res.code != 200) {
      console.log(res)
      if (res.code === 401) {
        // to re-login
        MessageBox.confirm('您的token已失效，您可以点击取消留在此页面，也可重新登录', '确认登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        })
      }else if(res.code === 204){
        Message({
          message: res.status,
          type: 'warning',
          duration: 5 * 1000
        })
        return res
      }else{
        Message({
          message: '服务器异常！',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(res.status || 'Error')
    } else {
      return res
    }
  },
  error => {
    // Notification.error({
    //   title: '错误',
    //   message: error
    // });
    return Promise.reject(error)
  }
)

export default service
